package com.crmeb.crmebcollect;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Presentation;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaRouter;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;

import com.crmeb.jsbridge.IJsCallBack;
import com.crmeb.jsbridge.JsBridgeApi;
import com.crmeb.jsbridge.JsMessageBean;
import com.crmeb.jsbridge.JsonUtil;
import com.sunmi.peripheral.printer.InnerPrinterCallback;
import com.sunmi.peripheral.printer.InnerPrinterException;
import com.sunmi.peripheral.printer.InnerPrinterManager;
import com.sunmi.peripheral.printer.SunmiPrinterService;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class CrmebCollectActicity extends AppCompatActivity {

    // 网页容器
    private WebView webView;

    // js 和 Java 交互
    private JsBridgeApi mJsBridgeApi;

    // 商米 服务
    private SunmiPrinterService sunmiPrinterService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_crmeb_collect2);
        AssetManager assetManager=this.getAssets(); //获取assets下内容
        // Remove the action bar
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        // Set the activity to fullscreen
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // web view
        webView = new WebView(this);
        setContentView(webView);
        webView.clearCache(Boolean.TRUE);
        // 初始化SunMi
        // 初始化商米驱动
        initSunmiPrinterService(CrmebCollectActicity.this);

        WebSettings webSettings = webView.getSettings();
        webSettings.setAllowUniversalAccessFromFileURLs(true);
//        WebSettings webSettings = webView.getSettings();
        // 让WebView能够执行javaScript
        webSettings.setJavaScriptEnabled(true);
        // 让JavaScript可以自动打开windows
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 设置缓存模式,一共有四种模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        // 设置缓存路径
//        webSettings.setAppCachePath("");
        // 支持缩放(适配到当前屏幕)
        webSettings.setSupportZoom(true);
        // 将图片调整到合适的大小
        webSettings.setUseWideViewPort(true);
        // 支持内容重新布局,一共有四种方式
        // 默认的是NARROW_COLUMNS
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        // 设置可以被显示的屏幕控制
        webSettings.setDisplayZoomControls(true);
        // 设置默认字体大小
        webSettings.setDefaultFontSize(12);
        // 开启Storege
        webSettings.setDomStorageEnabled(Boolean.TRUE);
        // 开启本地存储
        webSettings.setDatabaseEnabled(Boolean.TRUE);
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                Toast.makeText(getApplicationContext(),"url:"+url + "| message:"+message,Toast.LENGTH_SHORT).show();
                return super.onJsAlert(view, url, message, result);
            }
        });
        webView.setWebViewClient(new WebViewClient(){
        });
        webView.loadUrl("file:///android_asset/pro_collect/cashier.html#/cashier/cashier/index");

        // 顾显声明 第一次 显示Welcome 图片
        MediaRouter mediaRouter = (MediaRouter) this.getSystemService(Context.MEDIA_ROUTER_SERVICE);
        MediaRouter.RouteInfo route = mediaRouter.getSelectedRoute(MediaRouter.ROUTE_TYPE_LIVE_VIDEO);
        if (route != null) {
            Display presentationDisplay = route.getPresentationDisplay();
            if (presentationDisplay != null) {
                Presentation presentation = new MyPresentation(this, presentationDisplay);
                presentation.show();
//                Presentation presentation = new MyPresentation(CrmebCollectActicity.this, presentationDisplay);
                ImageView iv = new ImageView(CrmebCollectActicity.this);
                try {
                    InputStream inputStream = assetManager.open("gx.jpeg");
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    iv.setImageBitmap(bitmap);
                    presentation.setContentView(iv);
                    presentation.show();
                }  catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        MediaRouter.RouteInfo finalRoute = route;
        mJsBridgeApi = new JsBridgeApi(webView, new IJsCallBack() {
            @Override
            public void onJsCall(JsMessageBean jsMessageBean) {
//                Log.v("onJsCall", JsonUtil.toJsonString(jsMessageBean));
//                Toast.makeText(getApplicationContext(),"js call native "+JsonUtil.toJsonString(jsMessageBean),Toast.LENGTH_SHORT).show();
                // 在此判断js 调用的java 原生方法
                // 打开钱箱
                if(jsMessageBean.method.equals("openCacheBox")){
//                    Toast.makeText(getApplicationContext(),"执行打开钱箱操作--》JS --JAVA" + JsonUtil.toJsonString(jsMessageBean),Toast.LENGTH_SHORT).show();
                    openCashBox();
                }
//                 收银员登录成功后打开顾显
                if(jsMessageBean.method.equals("collectLoginSuccess")){
//                    Toast.makeText(getApplicationContext(),"收银员登录成功--》JS --JAVA111" + JsonUtil.toJsonString(jsMessageBean),Toast.LENGTH_SHORT).show();
                    if(finalRoute != null){
                        // 顾显显示收银台
                        Display presentationDisplay = finalRoute.getPresentationDisplay();
                        if(presentationDisplay != null){
                            Presentation presentation = new MyPresentation(CrmebCollectActicity.this, presentationDisplay);
                            WebView webView_customer = new WebView(CrmebCollectActicity.this);
                            WebSettings webSettingsCus = webView_customer.getSettings();
                            webSettingsCus.setJavaScriptEnabled(true);
                            presentation.setContentView(webView_customer);
                            webSettingsCus.setSupportZoom(true);
                            // 将图片调整到合适的大小
                            webSettingsCus.setUseWideViewPort(true);
                            webSettingsCus.setCacheMode(WebSettings.LOAD_DEFAULT);
                            // 默认的是NARROW_COLUMNS
                            webSettingsCus.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                            // 设置可以被显示的屏幕控制
                            webSettingsCus.setDisplayZoomControls(true);
                            // 开启Storege
                            webSettingsCus.setDomStorageEnabled(Boolean.TRUE);
                            // 开启本地存储
                            webSettingsCus.setDatabaseEnabled(Boolean.TRUE);
                            webView_customer.setWebChromeClient(new WebChromeClient());
                            webView_customer.setWebViewClient(new WebViewClient());

                            webView_customer.loadUrl("file:///android_asset/pro_collect/cashier.html#/cashier/auxScreen/index");
                            presentation.show();
                        }
                    }
//                 收银员注销后关闭顾显 业务数据显示
                    if(jsMessageBean.method.equals("collectLogout")){
//                    Toast.makeText(getApplicationContext(),"收银员登出成功--》JS --JAVA" + JsonUtil.toJsonString(jsMessageBean),Toast.LENGTH_SHORT).show();
                        Display presentationDisplay = finalRoute.getPresentationDisplay();
                        if(presentationDisplay != null){
                            Presentation presentation = new MyPresentation(CrmebCollectActicity.this, presentationDisplay);
                            ImageView iv = new ImageView(CrmebCollectActicity.this);
                            try {
                                InputStream inputStream = assetManager.open("gx.jpeg");
                                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                                iv.setImageBitmap(bitmap);
                                presentation.setContentView(iv);
                                presentation.show();
                            }  catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    mJsBridgeApi.notifyNativeTaskFinished("sf", jsMessageBean.id);
                }
            }
        });
        mJsBridgeApi.openJsBridgeChannel(webView);
        WebView.setWebContentsDebuggingEnabled(true);
        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (webView.canGoBack()) {
                    webView.goBack();
                    return true;
                } else {
                    return false;
                }
            }
        });


    }


    /////////////////////////////////////////////////// For SUNMI START

    private final InnerPrinterCallback innerPrinterCallback = new InnerPrinterCallback() {
        @Override
        protected void onConnected(SunmiPrinterService service) {
            sunmiPrinterService = service;
//            checkSunmiPrinterService(service);
        }

        @Override
        protected void onDisconnected() {
            sunmiPrinterService = null;
//            sunmiPrinter = LostSunmiPrinter;
        }
    };

    /**
     * init sunmi print service
     */
    public void initSunmiPrinterService(Context context){
        try {
            InnerPrinterManager instance = InnerPrinterManager.getInstance();
            if(instance != null){
                boolean ret =  InnerPrinterManager.getInstance().bindService(context,
                        innerPrinterCallback);
                if(!ret){
//                sunmiPrinter = NoSunmiPrinter;
//                Toast.makeText(CrmebCollectActicity.this, "初始化钱箱服务失败", Toast.LENGTH_LONG).show();
                }
            }

        } catch (InnerPrinterException e) {
            e.printStackTrace();
        }
    }



    public void openCashBox(){
        if(sunmiPrinterService == null){
            //TODO Service disconnection processing
            return;
        }

        try {
            sunmiPrinterService.openDrawer(null);
        } catch (RemoteException e) {
            Toast.makeText(CrmebCollectActicity.this,"Exception:"+e.getMessage(),Toast.LENGTH_LONG).show();
        }
    }

    /////////////////////////////////////////////////// For SUNMI END
}